const express = require('express');
const articleService = require('../service/ArticleService')
const ResultUtil = require('../utils/ResultUtil')

/**
 * 业务控制层： 查询文章列表
 * @param {*} req 
 * @param {*} res 
 */
const seletArticleList = async (req, res) => {
  const article = req.query
  let articleList = null
  try {
    articleList = await articleService.selecArticleList(article)
    res.send(ResultUtil.success(200).add(articleList))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 根据文章id查询文章信息
 * @param {*} req 
 * @param {*} res 
 */
const selectArticleById = async (req, res) => {
  const { id } = req.params
  console.log(req.params)
  try {
    const article = await articleService.selectArticleById(id)
    res.send(ResultUtil.success(200, article))
  } catch (error) {
    res.send(ResultUtil.error(500, error.message))
  }
}

/**
 * 业务控制层： 添加文章
 * @param {*} req 
 * @param {*} res 
 */
const addArticle = async (req, res) => {
  const article = req.body
  article.createdAt = new Date()
  console.log(article)
  try {
    await articleService.addArticle(article)
    res.send(ResultUtil.success(201, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 更新文章
 * @param {*} req 
 * @param {*} res 
 */
const updateArticle = async (req, res) => {
  const article = req.body
  article.updatedAt = new Date()
  try {
    await articleService.updateArticle(article)
    res.send(ResultUtil.success(208, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

/**
 * 业务控制层： 删除文章
 * @param {*} req 
 * @param {*} res 
 */
const deleteArticle = async (req, res) => {
  const { id } = req.body
  console.log(id, '删除文章')
  try {
    await articleService.deleteArticle(id)
    res.send(ResultUtil.success(204, true))
  } catch (e) {
    res.send(ResultUtil.error(500, e.message))
  }
}

module.exports = {
  seletArticleList,
  addArticle,
  updateArticle,
  deleteArticle,
  selectArticleById
}